package org.nepu.su.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Validator;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.lboot.core.auth.anno.AuthLogin;
import org.lboot.core.domain.ResponseDTO;
import org.lboot.jpa.entity.BaseEntity;
import org.lboot.jpa.utils.JpaDataUtil;
import org.nepu.sc.dict.SafeRateDict;
import org.nepu.sc.dict.SafeRateDictService;
import org.nepu.sc.dict.params.SafeRateDictImportParams;
import org.nepu.sc.dict.params.SafeRateDictParams;
import org.nepu.sc.dict.params.SafeRateDictQueryParams;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("safe")
@Api(tags = "评价指标管理")
@AllArgsConstructor
public class SafeRateDictController {
    SafeRateDictService dictService;


    @AuthLogin
    @PostMapping("dicts")
    @ApiOperation(value = "指标新建/更新")
    public ResponseDTO<Object> dictSet(@Validated @RequestBody SafeRateDictParams params){
        String rateId = params.getRateId();
        int level = rateId.length();
        List<SafeRateDict> dicts = dictService.getByRateId(rateId);
        if (dicts.isEmpty()){
            SafeRateDict dict = new SafeRateDict();
            BeanUtil.copyProperties(params, dict, CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
            dict.setRateLevel(level);
            return ResponseDTO.succData(
                    dictService.saveOne(dict)
            );
        }else {
            SafeRateDict dict = dicts.get(0);
            dict.setRateName(params.getRateName());
            return ResponseDTO.succData(
                    dictService.updateOne(dict)
            );
        }
    }

    @AuthLogin
    @DeleteMapping("dicts/{id}")
    @ApiOperation(value = "指标删除")
    public ResponseDTO<Object> dictDelete(@PathVariable("id") String id){
        dictService.deleteOne(id);
        return ResponseDTO.succMsg("删除成功");
    }


    @AuthLogin
    @GetMapping("dicts")
    @ApiOperation(value = "指标列表")
    public ResponseDTO<Object> dictList(SafeRateDictQueryParams params){
        Pageable pageable = JpaDataUtil.buildPageable(params);
        // 组合查询
        Specification<SafeRateDict> spec = (root, query, cb) -> {
            return cb.like(root.get("rateId"),params.getSearchKey()+"%");
        };
        if (Validator.isEmpty(params.getSearchKey())){
            return ResponseDTO.succData(
                    dictService.getAll(pageable)
            );
        }else {
            return ResponseDTO.succData(
                    dictService.getAll(pageable,spec)
            );
        }
    }


    @AuthLogin
    @PostMapping("dicts/clean")
    @ApiOperation(value = "指标清空")
    public ResponseDTO<Object> dictClean(){
        List<SafeRateDict> dicts = dictService.getAll();
        List<String> batchIds = dicts.stream().map(BaseEntity::getId).collect(Collectors.toList());
        dictService.batchDelete(batchIds);
        return ResponseDTO.succMsg("清空完成");
    }


    @AuthLogin
    @SneakyThrows
    @PostMapping("dicts/import")
    @ApiOperation(value = "指标导入")
    public ResponseDTO<Object> dictImport(SafeRateDictImportParams params){
        MultipartFile file = params.getFile();
        // 1. 读取文件内容
        String content = new String(file.getBytes());

        // 2. 使用 Jackson ObjectMapper 解析 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, String> jsonMap = objectMapper.readValue(content, new TypeReference<Map<String, String>>() {});
        //3. 查询已有的 新建/更新
        List<SafeRateDict> dicts = new ArrayList<>();
        for (String key:jsonMap.keySet()){
            SafeRateDict dict = new SafeRateDict();
            dict.setRateId(key);
            dict.setRateLevel(key.length());
            dict.setRateName(jsonMap.get(key));
            dicts.add(dict);
        }
        // 批量写入
        dictService.batchSave(dicts);
        return ResponseDTO.succMsg("导入成功");
    }


    @AuthLogin
    @DeleteMapping("dicts/batch")
    @ApiOperation(value = "根据前缀批量删除")
    public ResponseDTO<Object> batchDelete(@RequestParam("prefix") String prefix){
        // 根据前缀批量删除
        List<SafeRateDict> dicts = dictService.getAll();
        // 构建删除列表
        List<String> batchDeleteIds = new ArrayList<>();
        for (SafeRateDict dict:dicts){
            String rateId = dict.getRateId();
            if (rateId.startsWith(prefix)){
                batchDeleteIds.add(dict.getId());
            }
        }
        dictService.batchDelete(batchDeleteIds);
        return ResponseDTO.succMsg("删除成功");
    }
}
